<script setup lang="ts">
import { ref } from 'vue';
import { quasarFormStyle } from '@/setting.ts';
import type { PermissionList } from '@/api/acl/permission-type';
import { useQuasar, QForm } from 'quasar';
import { useCompRef } from '@/utils/useCompRef';
import type { ShowDialogFn } from '../type.ts';
import { reqSaveOrUpdatePermission } from '@/api/acl/permission.ts';

const { notify } = useQuasar();
const $emit = defineEmits<{
  refreshData: [flag?: string];
}>();
enum TITLE {
  SAVE = '新增',
  UPDATE = '修改'
}
const SUB_TITLE = ['一级菜单', '二级菜单', '三级菜单', '功能'];
// 类型
const dialogType = ref<'SAVE' | 'UPDATE' | 'DELETE'>();
// 等级
const level = ref<number>();
// 显示dialog
const isShowDialog = ref<boolean>(false);
// 菜单信息
const permissionInfo = ref<PermissionList>();
const showFormDialog: ShowDialogFn = (type, permission) => {
  dialogType.value = type;
  if (type === 'SAVE') {
    permissionInfo.value = permission;
  } else {
    permissionInfo.value = JSON.parse(JSON.stringify(permission));
  }
  level.value = permission.level - 1;
  isShowDialog.value = true;
};
defineExpose({ showFormDialog });

const qFormCom = useCompRef(QForm);
// 提交数据
async function onSubmit() {
  const error = await qFormCom.value?.validate();
  if (!error) return;
  try {
    const result = await reqSaveOrUpdatePermission(permissionInfo.value!);
    if (result.code === 200) {
      notify({
        type: 'positive',
        message: '操作成功',
        position: 'top'
      });
      $emit('refreshData', 'ok');
      isShowDialog.value = false;
    } else {
      throw new Error(result.data || '操作失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
</script>

<template>
  <q-dialog v-model="isShowDialog">
    <q-card>
      <q-card-section>
        <span class="text-h6">
          {{ TITLE[dialogType!] + SUB_TITLE[level!] }}
        </span>
      </q-card-section>
      <q-card-section>
        <q-form
          class="q-pl-lg q-gutter-xs"
          ref="qFormCom"
          style="min-width: 300px"
        >
          <q-input
            v-bind="quasarFormStyle"
            dense
            label="名称"
            v-model="permissionInfo!.name"
            :rules="[val => !!val || '名称不能为空']"
          />
          <q-input
            v-bind="quasarFormStyle"
            dense
            label="权限值"
            v-model="permissionInfo!.code"
            :rules="[val => !!val || '权限值不能为空']"
          />
        </q-form>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn
          label="取消"
          color="primary"
          flat
          @click="isShowDialog = false"
        />
        <q-btn label="提交" color="primary" @click="onSubmit" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss"></style>
